import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { CRuquestInterceptors, CRuquestConfig } from './type'
import { ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'
class CService {
  instance: AxiosInstance
  interceptor?: CRuquestInterceptors
  loading?: LoadingInstance
  showLoading: boolean
  constructor(config: CRuquestConfig) {
    // 创建实例
    this.instance = axios.create(config)
    // 设置拦截器
    this.interceptor = config.interceptors
    this.showLoading = config.showLoading ?? true
    // 1.从config里面获取拦截器并进行使用
    this.instance.interceptors.request.use(
      this.interceptor?.requestInterceptor,
      this.interceptor?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptor?.responseInterceptor,
      this.interceptor?.responseInterceptorCatch
    )
    // 2.添加所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            text: '正在获取...',
            background: 'rgba(0,0,0,0.5)'
          })
        }

        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        // 将loading移除
        setTimeout(() => {
          this.loading?.close()
        }, 500)
        const data = res.data
        if (data.code === '-1001') {
          console.log('请求失败~ 错误信息')
        } else {
          return data
        }
      },
      (err) => {
        // 将loading移除
        setTimeout(() => {
          this.loading?.close()
        }, 500)
        return err
      }
    )
  }
  request<T>(config: CRuquestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.requestInterceptor) {
            config = config.interceptors.requestInterceptor(config)
          }
          // console.log(res)
          resolve(res)
          this.showLoading = true
        })
        .catch((err) => {
          this.showLoading = true
          reject(err)
        })
    })
  }
  get<T>(config: CRuquestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T>(config: CRuquestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
}

export default CService
